<template>
  <span class="typewriter">{{ displayText }}</span>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'

const props = defineProps({
  text: {
    type: Array,
    required: true
  },
  delay: {
    type: Number,
    default: 2000
  }
})

const displayText = ref('')
let currentIndex = 0
let charIndex = 0
let timer = null

const typeText = () => {
  const currentText = props.text[currentIndex]
  
  if (charIndex < currentText.length) {
    displayText.value = currentText.substring(0, charIndex + 1)
    charIndex++
    timer = setTimeout(typeText, 100)
  } else {
    timer = setTimeout(() => {
      eraseText()
    }, props.delay)
  }
}

const eraseText = () => {
  if (charIndex > 0) {
    displayText.value = props.text[currentIndex].substring(0, charIndex - 1)
    charIndex--
    timer = setTimeout(eraseText, 50)
  } else {
    currentIndex = (currentIndex + 1) % props.text.length
    timer = setTimeout(typeText, 500)
  }
}

onMounted(() => {
  typeText()
})

onUnmounted(() => {
  if (timer) {
    clearTimeout(timer)
  }
})

watch(() => props.text, () => {
  if (timer) {
    clearTimeout(timer)
  }
  currentIndex = 0
  charIndex = 0
  typeText()
})
</script>

<style scoped>
.typewriter {
  border-right: 2px solid;
  animation: blink 0.75s step-end infinite;
  padding-right: 4px;
}

@keyframes blink {
  from, to { border-color: transparent }
  50% { border-color: currentColor }
}
</style>
